/*
 * @Author: AskMeWhy
 * @Date: 2020-12-27 11:58:47
 * @Last Modified by: AskMeWhy
 * @Last Modified time: 2020-12-29 11:37:33
 */
const app = getApp();
const {AskComponent} = app._require("common/index");

AskComponent({
    properties: {
        list: {
            type: Array,
            value: [],
        },
        status: {
            type: String,
            value: "",
        },
        orgCategoryId: {
            type: String,
            value: app.user.userInfo.orgCategoryId
        }
    },
    data: {
        bottomItems: [{"title": "填报", "color": "#4287FC"},
            {"title": "提交", "color": "#4287FC"}, {"title": "转发", "color": "#4287FC"}],

        bottomEndItems: [],
        bottomApprovalItems: [{"title": "审批", "color": "#4287FC"}],
        share: {
            show: false,
            item: null,
            list: [
                {name: "转发给其他人填报", value: "orgOut", openType: "share", taskId: ""},],
        },
        actions: [{name: '审批通过', color: '#333333'}, {name: '驳回', color: '#333333'},],
        approveShow: false,
        approvePopShow: false,

    },
    lifetimes: {
        attached() {
        },
        detached() {
            // 在组件实例被从页面节点树移除时执行
        },
    },
    methods: {
        handleClick(e) {
        },
        itemClick(e) {
            var index = e.currentTarget.dataset.itemindex;
            var item = e.currentTarget.dataset.item;
            var key = e.currentTarget.dataset.key.title;
            if (key == "转发") {
                this.$emit("zf", {data: item})
            } else if (key == "提交") {
                this.onFillAction(item, index);
            } else if (key == "填报") {
                try {
                    let pagetotal = getCurrentPages() //所有的路径 数组
                    let thispage = pagetotal[pagetotal.length - 1] //当前页面
                    // let parpage = pagetotal[pagetotal.length - 2] //父级页面
                    thispage.setData({
                        'currentIndex': index
                    })
                } catch (e) {
                }
                this.onFill(item);
            } else if (key == "查看" || key == "审批") {

                wx.navigateTo({
                    url: "/pages/declare-view/index?item=" + JSON.stringify(item) + "&formName=" + item.source.formName + "&departmentName=" + item.source.creatorDepartmentName + "&createTime=" + item.source.createTime + "&deadTime=" + item.source.endDate + "&formId=" + item.source.formId + "&state=" + item.state.state + "&id=" + item.source.id + "&approvalStatus=" + item.source.approvalStatus + "&category=" + item.source.category + "&processInstanceId=" + item.source.processInstanceId,
                    events: {
                        updateDataAction: () => {
                            this.$emit("reloadData", {});
                        }
                    }
                });
            } else if (key == "审批") {
            }
        },
        //分享
        onShare(e) {
            let item = e;
            // let { value: item } = e.detail;
            let auth = this.checkAuth();
            if (!auth) return;
            this.data.share.item = item;
            this.setData({
                "share.show": true,
            });
        },
        onShareChange(e) {
            let {value} = e.detail;
            if (value === "orgIn") {
                wx.navigateTo({
                    url: "/pages/plugins/transfer-org/index",
                    events: {
                        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                        sure: data => {
                            this.sendTask({detail: data});
                        },
                    },
                    success: res => {
                    },
                });
            }
            console.log("onShareChange", e);
        },
        onShareClose() {
            this.setData({
                "share.show": false,
            });
        },
        //提交
        onFillAction(e, itemindex) {

            this.$emit("onfill", {
                item: e,
                index: itemindex
            });

        },
        updateTask(e) {
            let auth = this.checkAuth();
            if (!auth) return;
            let item = e;
            const _page = this.getPage();
            let status = {
                value: "",
            };
            let info = {
                msg: "任务已完成",
                errMsg: "状态修改失败",
            };
            if (_page) {
                status = _page.$key2Name(
                    {
                        type: "EXECUTING",
                        name: "state",
                        list: _page.data.taskStateList,
                    },
                    "obj"
                );
            }
            this.updateAudit(item, status.state, info, () => {
                const _page = this.getPage();
                if (_page) {
                    _page.loginSuccess();
                }
                this.onFill({
                    detail: {
                        value: {
                            ...item,
                            state: status,
                        },
                    },
                });
            });
        },
        //填报
        onFill(e) {
            const userInfo = (app.user && app.user.userInfo) || {};
            let auth = this.checkAuth();
            if (!auth) return;
            let item = e;
            wx.navigateTo({
                url: "/pages/home/collection/collection-details/index?formId=" + item.source.formId + "&dataCount=" + item.source.dataCount + "&processInstanceId=" + item.source.processInstanceId + "&userId=" + userInfo.id + "&goBackLast=true"
            });
        },
        //查看
        async onEnd(e) {
            // console.log(e);
            let auth = this.checkAuth();
            if (!auth) return;
            let item = e;
            let info = {
                msg: "任务已完成",
                errMsg: "状态修改失败"
            }
            try {
                const response = await this.$_server("task/finish", {
                    data: {
                        taskId: item.id
                    },
                });
                let {data} = response;
                if (data.code !== 200) {
                    throw data;
                }
                wx.askShowToastEx({
                    mask: true,
                    title: info.msg || "状态已更新",
                    icon: "none",
                    duration: 2000,
                    cancel: () => {
                        const _page = this.getPage();
                        if (_page) {
                            _page.loginSuccess();
                        }
                    },
                });
            } catch (error) {
                console.log(error);
                // statements
                if (error.message) {
                    wx.showToast({
                        mask: true,
                        title: error.message || info.errMsg,
                        icon: "none",
                        duration: 2000,
                    });
                } else {
                    throw error;
                }
            }
        },
        async updateAudit(item, status, info, callback) {
            try {
                const response = await this.$_server("task/audit", {
                    data: {
                        id: item.id,
                        status
                    }
                });
                let {data} = response;
                if (data.code !== 200) {
                    throw data;
                }
                if (callback) {
                    callback();
                } else {
                    wx.askShowToastEx({
                        mask: true,
                        title: info.msg || "状态已更新",
                        icon: "none",
                        duration: 2000,
                        cancel: () => {
                            const _page = this.getPage();
                            if (_page) {
                                _page.loginSuccess();
                            }
                        },
                    });
                }
            } catch (error) {
                console.log(error);
                // statements
                if (error.message) {
                    wx.showToast({
                        mask: true,
                        title: error.message || info.errMsg,
                        icon: "none",
                        duration: 2000,
                    });
                } else {
                    throw error;
                }
            }
        },
        async sendTask(e) {
            try {
                let {actives} = e.detail;
                let {item} = this.data.share;
                const response = await this.$_server("task/sendTask", {
                    data: {
                        id: item.id,
                        userId: actives.join(",")
                    }
                });
                let {data} = response;
                if (data.code !== 200) {
                    throw data;
                }
                wx.askShowToastEx({
                    mask: true,
                    title: "任务已转发",
                    duration: 2000,
                    icon: "none",
                    cancel: () => {
                        const _page = this.getPage();
                        if (_page) {
                            _page.loginSuccess();
                        }
                    },
                });
            } catch (error) {
                console.log(error);
                // statements
                if (error.message) {
                    wx.showToast({
                        mask: true,
                        title: error.message,
                        icon: "none",
                        duration: 2000,
                    });
                } else {
                    throw error;
                }
            }
        },
        approvedTask(e, index) {
            console.log(e);
            let dataCount = e.source.dataAllCount ? e.source.dataAllCount : 0;
            this.setData({
                approvePopShow: true,
                "currentItem": e,
                "approveDesc": "已采集数据" + dataCount + "份",
                "itemIndex": index,
            })
        },
        actionEnd(e) {
            let index = parseInt(e.detail);
            let list = this.data.list;
            list.splice(index, 1)
            console.log(list, index);
            this.setData({
                "list": list
            })
        },
        clickDetailsAction(e) {
            console.log(e);
            let item = e.currentTarget.dataset.item;
            let index = e.currentTarget.dataset.index;
            try {
                let pagetotal = getCurrentPages() //所有的路径 数组
                let thispage = pagetotal[pagetotal.length - 1] //当前页面
                thispage.setData({
                    'currentIndex': index
                })
            } catch (e) {
            }
            wx.navigateTo({
                url: "/pages/declare-view/index?item=" + JSON.stringify(item) + "&formName=" + item.source.formName + "&departmentName=" + item.source.creatorDepartmentName + "&createTime=" + item.source.createTime + "&deadTime=" + item.source.endDate + "&formId=" + item.source.formId + "&state=" + item.state.state + "&id=" + item.source.id + "&approvalStatus=" + item.source.approvalStatus + "&category=" + item.source.category + "&processInstanceId=" + item.source.processInstanceId,
                events: {
                    updateDataAction: () => {
                        this.$emit("reloadData", {});
                    }
                }
            });
        }
    },
});
